//
//  JOrderController.m
//  HeadIndustry
//
//  Created by jun on 2017/9/8.
//  Copyright © 2017年 jun. All rights reserved.
//

#import "JOrderController.h"
#import "JWaitPayView.h"
#import "JProductDetailController.h" 
#import "JOrderDetailController.h" // 订单详情

#import "JCommentController.h" // 添加评论
#import "JLookGoodsController.h" // 查看物流
#import "JGroupGoodsDetailController.h" // 商品团购待付款详情
#import "JVerdorController.h" // 普通店铺详情
#import "JCutHairDetailController.h" // 团购理发店店铺详情

#define orderBtnTag 100


@interface JOrderController ()<UIScrollViewDelegate, JWaitPayViewDelegate>

//@property (nonatomic, strong) UIView *emptyBGView;
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, assign) CGFloat btnWidth;
@property (nonatomic, assign) NSInteger lastBtnSel;

@property (nonatomic, strong) UIScrollView *scrollView;

@property (nonatomic, strong) NSMutableArray *dataEmptyViewArr;
@property (nonatomic, strong) NSMutableArray *dataViewArr;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *dataGroupArr;

@end

@implementation JOrderController

- (void)viewDidLoad {
    [super viewDidLoad];
    [super InitUI];
    
    
    [self configBgView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData) name:OrderRefresh object:nil];
    
}

- (void)reloadData
{
    [self loadWaitPayOrderInfoRequedt:_lastBtnSel];
    [self loadGroupWaitPayOrderInfoRequedt:_lastBtnSel];
}

- (void)configBgView
{
    self.titleLabel.text = @"我的订单";
    self.leftButton.hidden = NO;
    self.rightButton. hidden = YES;
    [self.leftButton setImage:[UIImage imageNamed:backBtnImg] forState:UIControlStateNormal];
    self.leftButton.frame = CGRectMake(8, self.leftButton.frame.origin.y, 30, 30);
    [self configTopView];
    
    [self configScrollView];
    
    _lastBtnSel = _numPage;
    
    [self lineViewAnimation:_lastBtnSel];
    
    
    [self loadWaitPayOrderInfoRequedt:_lastBtnSel];
    [self loadGroupWaitPayOrderInfoRequedt:_lastBtnSel];
    [_scrollView setContentOffset:CGPointMake(_lastBtnSel * kWindowW, 0) animated:NO];
}

- (void)setupCartEmptyView:(UIScrollView *)scrollView rect:(CGRect)rect{
    //默认视图背景
    UIView *backgroundView = [[UIView alloc]init];
//    backgroundView.frame = CGRectMake(0, 0, kWindowW, CGRectGetHeight(self.contentView.frame));
    backgroundView.frame = rect;
    [scrollView addSubview:backgroundView];
    backgroundView.hidden = YES;
    [self.dataEmptyViewArr addObject:backgroundView];
    //默认图片
    UIImageView *img = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"order_empty"]];
    img.center = CGPointMake(kWindowW/2.0, kWindowH/2.0 - 120);
    img.bounds = CGRectMake(0, 0, 100, 100);
    [backgroundView addSubview:img];
    
    UILabel *warnLabel = [[UILabel alloc]init];
    warnLabel.center = CGPointMake(kWindowW/2.0, kWindowH/2.0 - 10);
    warnLabel.bounds = CGRectMake(0, 0, kWindowW, 60);
    warnLabel.textAlignment = NSTextAlignmentCenter;
    warnLabel.text = @"您还没有相关订单";
    warnLabel.numberOfLines = 0;
    warnLabel.font = [UIFont systemFontOfSize:16];
    warnLabel.textColor = kRGBColor(150, 150 , 150);
    [backgroundView addSubview:warnLabel];
}

- (void)configTopView {
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWindowW, 50)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:bgView];
    _topView = bgView;
    
    NSArray *arrBtn = @[@"待付款",@"待收货",@"待评价",@"退换货",@"已结束"];
    _btnWidth = kWindowW /5.0;
    for (int i = 0; i <arrBtn.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(_btnWidth * i, 0, _btnWidth, _topView.height);
        [btn setTitle:arrBtn[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(orderBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        btn.titleLabel.font = kFONT_TITLE(16);
        btn.tag = orderBtnTag + i;
        [bgView addSubview:btn];
    }
    
    CALayer *lineLayer = [CALayer layer];
    lineLayer.backgroundColor = kRGBColor(150, 150, 150).CGColor;
    lineLayer.frame = CGRectMake(0, bgView.height - 0.5, kWindowW, 0.5);
    [bgView.layer addSublayer:lineLayer];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(15, bgView.height - 2, _btnWidth - 30, 2)];
    lineView.backgroundColor = [UIColor redColor];
    [bgView addSubview:lineView];
    _lineView = lineView;
}

- (void)configScrollView {
    _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, _topView.bottom, kWindowW, CGRectGetHeight(self.contentView.frame) - _topView.height)];
    _scrollView.contentSize = CGSizeMake(kWindowW * 5, _scrollView.height);
    _scrollView.delegate = self;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    [self.contentView addSubview:_scrollView];
    
    for (int i = 0; i < 5; i++) {
        JWaitPayView *orderView = [[JWaitPayView alloc] initWithFrame:CGRectMake(i*kWindowW, 0, kWindowW, _scrollView.height)];
        orderView.tag = i;
        orderView.delegate = self;
        [_scrollView addSubview:orderView];
        [self.dataViewArr addObject:orderView];
        
        CGRect rect = CGRectMake(i*kWindowW, 0, kWindowW, _scrollView.height);
        [self setupCartEmptyView:_scrollView rect:rect];
    }
    
}


- (void)loadWaitPayOrderInfoRequedt:(NSInteger)type
{
    [self.dataArr removeAllObjects];
    NSString *url = @"Orders/GetOrdersByCustomerId";
    
    NSInteger typeID;
    
    switch (type) {
        case 0:
            typeID = 1;
            break;
        case 1:
            typeID = 2;
            break;
        case 2:
            typeID = 3;
            break;
        case 3:
            typeID = 4;
            break;
        case 4:
            typeID = 9;
            break;
            
        default:
            typeID = 1;
            break;
    }
    [SVProgressHUD show];
    [JNetManager getUserWaitPayOrderInfoUrl:url
                                     typeID:typeID
                                    success:^(id response) {
                                        if (response) {
                                            NSArray *dataArr = (NSArray *)response;
                                            self.dataArr = [NSMutableArray arrayWithArray:dataArr];
                                            [SVProgressHUD dismiss];
                                            
                                            UIView *emptyView = self.dataEmptyViewArr[type];
                                            JWaitPayView *orderView = self.dataViewArr[type];
                                            orderView.selOrderType = type;
                                            orderView.dataArr = dataArr;
                                            
                                            if (dataArr.count > 0) {
                                                emptyView.hidden = YES;
                                                orderView.hidden = NO;
                                            }
                                            else if (self.dataGroupArr.count == 0)
                                            {
                                                emptyView.hidden = NO;
                                                orderView.hidden = YES;
                                            }
                                            
                                        }
                                    } failure:^(NSString *err) {
                                        [SVProgressHUD dismiss];

                                        [SVProgressHUD showErrorWithStatus:err];
                                    }];
}


- (void)loadGroupWaitPayOrderInfoRequedt:(NSInteger)type
{
    [self.dataGroupArr removeAllObjects];
    NSString *url = @"ServerOrder/GetServerOrders";
    
    NSInteger typeID;
    
    switch (type) {
        case 0:
            typeID = 10;
            break;
        case 1:
            typeID = 20;
            break;
        case 2:
            typeID = 40;
            break;
        case 3:
            typeID = 50;
            break;
        case 4:
            typeID = 100;
            break;
            
        default:
            typeID = 10;
            break;
    }
    [SVProgressHUD show];
    [JNetManager getGroupUserWaitPayOrderInfoUrl:url
                                          typeID:typeID
                                         success:^(id response) {
                                             if (response) {
                                                 NSArray *dataArr = (NSArray *)response;
                                                 self.dataGroupArr = [NSMutableArray arrayWithArray:dataArr];
                                                 [SVProgressHUD dismiss];
                                                 
                                                 
                                                 JWaitPayView *orderView = self.dataViewArr[type];
                                                 orderView.selOrderType = type;
                                                 orderView.dataGroupArr = dataArr;
                                                 
                                                 
                                                 UIView *emptyView = self.dataEmptyViewArr[type];
                                                 
                                                 if (dataArr.count > 0) {
                                                     emptyView.hidden = YES;
                                                     orderView.hidden = NO;
                                                 }
                                                 else if (self.dataArr.count == 0)
                                                 {
                                                     emptyView.hidden = NO;
                                                     orderView.hidden = YES;
                                                 }
                                                 
                                             }
                                         } failure:^(NSString *err) {
                                             [SVProgressHUD dismiss];
                                             
                                             [SVProgressHUD showErrorWithStatus:err];
                                         }];
    
}

#define mark - JWaitPayViewDelegate

// 进入订单详情
- (void)selectIndexPath:(NSIndexPath *)indexPath selOrderType:(NSInteger)type idModel:(id)model
{
    if (indexPath.section == 0) {
        if (type != 3)
        {
            JOrderDetailController *detailVC = [[JOrderDetailController alloc]init];
            detailVC.selType = type;
            detailVC.waitPayModel = model;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
       
    }
    else{
        if (type != 3)
        {
            JGroupGoodsDetailController *detailVC = [[JGroupGoodsDetailController alloc]init];
            detailVC.selType = type;
            detailVC.groupmodel = model;
            [self.navigationController pushViewController:detailVC animated:YES];
        }
    }
}

// 取消订单
- (void)cancleOrderMethod:(id)payModel
{
    [self cancelOrder:payModel];
}

// 进入店铺
- (void)goVerdorShopMethod:(id)payModel
{
    if ([payModel isKindOfClass:[JWaitPayModel class]]) {
        JWaitPayModel *model = payModel;
        JVerdorController *verdor = [[JVerdorController alloc] init];
        verdor.verdorID = model.VendorId;
        [self.navigationController pushViewController:verdor animated:YES];
    }
    else
    {
        JOrderGroupModel *model = payModel;
        JCutHairDetailController *verdor = [[JCutHairDetailController alloc] init];
        verdor.CutHairShopId = model.BarberShopId;
        [self.navigationController pushViewController:verdor animated:YES];
    }

}

// 进入商品详情
- (void)selTypeThireInputProductDetailVC:(JWaitPayDetailModel *)payDetailModel
{
    JProductDetailModel *detailModel = [JProductDetailModel new];
    detailModel.Id = payDetailModel.ProductId;

    JProductDetailController *detail = [[JProductDetailController alloc]init];
    detail.productModel = detailModel;
    detail.inputType = 1; // 表示非购物车进入商品详情
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}
// 订单付款
- (void)OrderPayMethod:(id)payModel
{
    
    
    NSLog(@"前去付款");
//    NSString *url;
//    
//    if ([payModel isKindOfClass:[JWaitPayModel class]]) {
//        url = @"Orders/CancelOrder";
//    }
//    else
//    {
//        url = @"ServerOrder/CancelServerOrder";
//    }
}

// 查看物流
- (void)lookGoodsMethod:(id)payModel
{
    JLookGoodsController *detailVC = [[JLookGoodsController alloc]init];
    if ([payModel isKindOfClass:[JWaitPayModel class]]) {
        detailVC.waitPayModel = payModel;
    }
    [self.navigationController pushViewController:detailVC animated:YES];
}

// 订单评论
- (void)OrderCommentMethod:(id)payModel
{
    JCommentController *detailVC = [[JCommentController alloc]init];
    if ([payModel isKindOfClass:[JWaitPayDetailModel class]]) {
        detailVC.inputType = 0;
        detailVC.payModel = payModel;
        
    }
    else if ([payModel isKindOfClass:[JOrderGroupModel class]])
    {
        detailVC.inputType = 1;
        detailVC.groupModel = payModel;
        
    }
    [self.navigationController pushViewController:detailVC animated:YES];
    
    
}
// 退货
- (void)OrderRebackMethod:(id)payModel
{
//    NSString *url;
//    
//    if ([payModel isKindOfClass:[JWaitPayModel class]]) { // 非团购
//        
//        JWaitPayModel *model = payModel;
//        if ([model.OrderStatus isEqualToString:@"待发货"]) {
//            url = @"Orders/ReturnOrderItem"; // 待发货
//        }
//        else if ([model.OrderStatus isEqualToString:@"待收货"]) {
//            url = @"Orders/CreateReturnOrder"; // 待收货
//        }
//        
//    }
//    else // 团购
//    {
//        url = @"";
//    }
}
// 确认收货
- (void)OrderConfirmMethod:(id)payModel
{
    NSString *url;
    
    if ([payModel isKindOfClass:[JWaitPayModel class]]) {
        JWaitPayModel *model = payModel;
        model.OrderStatusId = 40;
        payModel = model;
        url = @"Orders/UpdateOrder"; // 确认收货
        
    }
    else
    {
        url = @"";
    }
    
    
    [JNetManager cancelOrderRequedtUrl:url
                          waitPatModel:payModel
                               success:^(id response) {
                                   if ([response integerValue] == 1) {
                                       [SVProgressHUD showSuccessWithStatus:@"确认收货成功"];
                                       
                                       // 刷新数据
                                       [self reloadData];
                                   }
                               } failure:^(NSString *err) {
                                   [SVProgressHUD showErrorWithStatus:err];
                               }];
    
}

- (void)cancelOrder:(id)model {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您确定取消该订单吗？" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *doneAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self cancelOrderRequedt:model];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alertVC addAction:doneAction];
    [alertVC addAction:cancelAction];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)cancelOrderRequedt:(id)model {
    NSString *url;
    
    if ([model isKindOfClass:[JWaitPayModel class]]) {
        url = @"Orders/CancelOrder";
    }
    else
    {
        url = @"ServerOrder/CancelServerOrder";
    }
    
    [JNetManager cancelOrderRequedtUrl:url
                          waitPatModel:model
                               success:^(id response) {
                                   if ([response integerValue] == 1) {
                                       [SVProgressHUD showSuccessWithStatus:@"取消成功"];
                                       
                                       // 刷新数据
                                       [self reloadData];
                                   }
                               } failure:^(NSString *err) {
                                   [SVProgressHUD showErrorWithStatus:err];
                               }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    NSInteger page = scrollView.contentOffset.x / scrollView.width;
    _lastBtnSel = page;
    [self lineViewAnimation:page];

    [self loadWaitPayOrderInfoRequedt:page];
    [self loadGroupWaitPayOrderInfoRequedt:page];

}

- (void)orderBtnClick:(UIButton *)btn
{
    if (btn.tag - orderBtnTag == _lastBtnSel) {
        return;
    }
    
    [self lineViewAnimation:btn.tag - orderBtnTag];
    _lastBtnSel = btn.tag - orderBtnTag;
    [_scrollView setContentOffset:CGPointMake(_lastBtnSel * kWindowW, 0) animated:YES];
    [self loadWaitPayOrderInfoRequedt:_lastBtnSel];
    [self loadGroupWaitPayOrderInfoRequedt:_lastBtnSel];

}

- (void)leftButtonClick:(UIButton *)leftButton
{
    [[NSNotificationCenter defaultCenter] postNotificationName:NSStringFromClass([JOrderController class]) object:nil];
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)lineViewAnimation:(NSInteger)num
{

    [UIView animateWithDuration:0.3 animations:^{
        _lineView.frame = CGRectMake(15 + num * _btnWidth, _lineView.origin.y, _lineView.width, _lineView.height);
    }];
}

- (NSMutableArray *)dataEmptyViewArr
{
    if (_dataEmptyViewArr == nil) {
        _dataEmptyViewArr = [NSMutableArray array];
    }
    return _dataEmptyViewArr;
}

- (NSMutableArray *)dataViewArr
{
    if (_dataViewArr == nil) {
        _dataViewArr = [NSMutableArray array];
    }
    return _dataViewArr;
}

- (NSMutableArray *)dataArr
{
    if (_dataArr == nil) {
        _dataArr = [NSMutableArray array];
    }
    return _dataArr;
}

- (NSMutableArray *)dataGroupArr
{
    if (_dataGroupArr == nil) {
        _dataGroupArr = [NSMutableArray array];
    }
    return _dataGroupArr;
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
